<script setup lang="ts" name="JobLog">
import logDetailPage from "./logDetail.vue";
import { onBeforeRouteLeave } from "vue-router";
import { cleanJobLogApi, getJobApi } from "@/api/monitor/job";
import { delJobLogApi, listJobLogApi } from "@/api/monitor/jobLog";
import { RouterRecord } from "@/global/record/RouterRecord";

const router = useRouter();

const route = useRoute();

const { proxy } = getCurrentInstance();

const { sys_job_group, sys_common_status } = useDict("sys_job_group", "sys_common_status");

// 加载
const loading = ref(false);

// 导出遮罩层
const exportLoading = ref(false);

// 搜索栏元素
const queryJobLogRef = ref(null);

// 表单Id
const id = ref(null);

// 选中数组
const selection = ref<JobLogRecord[]>([]);

// 非单个禁用
const single = ref(true);

// 非多个禁用
const multiple = ref(true);

// 切换搜索条件
const showSearch = ref(false);

// 调度日志列表
const jobLogList = ref<JobLogRecord[]>([]);

// 弹出层标题
const title = ref("");

// 编辑弹出层
const openEdit = ref(false);

// 详情弹出层
const openDetail = ref(false);

//总条数
const total = ref(0);

// 列信息
const columns = ref<TableColumnsRecord>({
  colNo: { label: "序号", visible: true },
  jobLogId: { label: "日志编号", visible: true },
  jobName: { label: "任务名称", visible: true },
  jobGroup: { label: "任务分组", visible: true },
  invokeTarget: { label: "调用目标字符串", visible: true },
  invokeTarget: { label: "调用方法", visible: true },
  jobMessage: { label: "日志信息", visible: true },
  status: { label: "执行状态", visible: true },
  exceptionInfo: { label: "异常信息", visible: true },
  createTime: { label: "执行时间", visible: true },
  operate: { label: "操作", visible: true }
});

// 查询参数
const queryParams = ref<JobLogRecord>({
  pageNum: 1,
  pageSize: 10,
  jobLogId: null,
  jobName: null,
  jobGroup: null,
  invokeTarget: null,
  invokeTarget: null,
  jobMessage: null,
  status: null,
  exceptionInfo: null,
  createTime: null,
});

// 执行时间选择
const dateRange = ref<[string, string]>(['', '']);

/** 获取定时任务详情 */
function getJobDetail() {
  if(route.query.jobId) {
    getJobApi(route.query.jobId).then(response => {
      queryParams.value.jobName = response.data.jobName;
      queryParams.value.jobGroup = response.data.jobGroup;
      getList();
    })
  }else {
    getList();
  }
}

/** 查询调度日志列表 */
function getList() {
  loading.value = true;
  listJobLogApi(addDateRange(queryParams.value, dateRange.value)).then(response => {
    jobLogList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    jobLogList.value.forEach((item, index) => {
      item['colNo'] = sequenceNo(index, queryParams.value);
    });
  });
}

/** 关闭弹窗 */
function closeDialog(refresh: boolean) {
  if (refresh) {
    getList();
  }
  openEdit.value = false;
  openDetail.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = ['', ''];
  queryJobLogRef.value.resetFields();
  handleQuery();
}

/** 切换按钮操作 */
function changSearch() {
  showSearch.value = !showSearch.value;
}

/** 多选框选中数据 */
function handleSelectionChange(selectionList: JobLogRecord[]) {
  selection.value = selectionList;
  single.value = selectionList.length !== 1;
  multiple.value = !selectionList.length;
}

/** 新增按钮操作 */
function handleAdd() {
  id.value = null;
  openEdit.value = true;
  title.value = "新增调度日志";
}

/** 修改按钮操作 */
function handleUpdate(row: JobLogRecord) {
  id.value = row.jobLogId;
  openEdit.value = true;
  title.value = "修改调度日志";
}

/** 详情按钮操作 */
function handleDetails(row: JobLogRecord) {
  id.value = row.jobLogId;
  openDetail.value = true;
  title.value = "调度日志详情";
}

/** 删除按钮操作 */
function handleDelete(row: JobLogRecord | any) {
  let ids = [];
  let colNos = [];
  if (row.jobLogId) {
    ids = [row.jobLogId];
    colNos = [row.colNo];
  } else {
    selection.value.forEach(item => {
      ids.push(item.jobLogId);
      colNos.push(item.colNo);
    });
  }

  // @ts-ignore
  proxy.$modal.confirm('是否确认删除序号为"' + colNos + '"的数据项?').then(() => {
    return delJobLogApi(ids);
  }).then(() => {
    getList();
    // @ts-ignore
    proxy.$modal.msgSuccess("删除成功");
  }).catch(err => {
    console.error(err)
  });
}

/** 清空按钮操作 */
function handleClean() {
  proxy.$modal.confirm("是否确认清空所有调度日志数据项?").then(function () {
    return cleanJobLogApi();
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("清空成功");
  }).catch(err => {
    console.error(err)
  });
}

/** 导出按钮操作 */
function handleExport() {
  download('monitor/jobLog/export', {
    ...queryParams.value
  }, `调度日志_${new Date().getTime()}.xlsx`);
}


/** 返回 */
function handleBack() {
  router.back();
}

onBeforeRouteLeave(() => {
  useTagsViewStore().delView(<RouterRecord>route);
})

getJobDetail();
</script>

<template>
  <div class="app-container">
    <div class="back-item">
      <el-form :model="queryParams" ref="queryJobLogRef" :inline="true" label-width="68px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input
              v-model="queryParams.jobName"
              placeholder="请输入任务名称"
              clearable
              @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="任务分组" prop="jobGroup">
          <el-select
              v-model="queryParams.jobGroup"
              placeholder="请选择任务分组"
              clearable
              @keyup.enter.native="handleQuery"
          >
            <el-option
                v-for="item in sys_job_group"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行状态" prop="status">
          <el-select
              v-model="queryParams.status"
              placeholder="请选择执行状态"
              clearable
              @keyup.enter.native="handleQuery"
          >
            <el-option
                v-for="item in sys_common_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="执行时间" prop="createTime">
          <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item class="item-search">
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button type="warning" icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="back-item">
      <div class="table-top mb8">
        <div class="title title-left">
          调度日志列表
        </div>
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-has-permi="['monitor:jobLog:remove']"
        >删除
        </el-button>
        <el-button
            type="danger"
            plain
            icon="Delete"
            @click="handleClean"
            v-hasPermi="['monitor:job:remove']"
        >清空</el-button>
        <el-button
            type="warning"
            plain
            icon="Download"
            :loading="exportLoading"
            @click="handleExport"
            v-has-permi="['monitor:jobLog:export']"
        >导出
        </el-button>
        <el-button
            type="warning"
            plain
            icon="Back"
            @click="handleBack"
        >返回
        </el-button>
        <span class="table-top-line" />
        <right-toolbar @queryTable="getList" :columns="columns" />
      </div>
      <el-table
          v-loading="loading"
          :data="jobLogList"
          stripe
          v-tablesticky
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" prop="colNo" align="center" width="55" v-if="columns.colNo.visible" />
        <el-table-column label="日志编号" prop="jobLogId" align="center" v-if="columns.jobLogId.visible" />
        <el-table-column label="任务名称" prop="jobName" align="center" min-width="140" show-overflow-tooltip v-if="columns.jobName.visible" />
        <el-table-column label="任务分组" prop="jobGroup" align="center" v-if="columns.jobGroup.visible">
          <template #default="scope">
            <dict-tag :options="sys_job_group" :value="scope.row.jobGroup" />
          </template>
        </el-table-column>
        <el-table-column label="调用目标字符串" prop="invokeTarget" align="center" min-width="160" show-overflow-tooltip
                         v-if="columns.invokeTarget.visible" />
        <el-table-column label="日志信息" prop="jobMessage" align="center" min-width="160" show-overflow-tooltip
                         v-if="columns.jobMessage.visible" />
        <el-table-column label="执行状态" prop="status" align="center" v-if="columns.status.visible">
          <template #default="scope">
            <dict-tag :options="sys_common_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="异常信息" prop="exceptionInfo" align="center" v-if="columns.exceptionInfo.visible" />
        <el-table-column label="执行时间" prop="createTime" align="center" min-width="160" v-if="columns.createTime.visible" />
        <el-table-column label="操作" prop="operate" align="center" fixed="right" width="120"
                         v-if="columns.operate.visible">
          <template #default="scope">
            <el-tooltip content="详情" placement="top">
              <el-button
                  link
                  type="primary"
                  icon="Document"
                  @click="handleDetails(scope.row)"
                  v-has-permi="['monitor:jobLog:query']"
              />
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
          :total="total"
          open-fixed
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          @pagination="getList"
      />
      <div class="line-magin" />
    </div>

    <!-- 添加或修改调度日志对话框 -->
    <log-detail-page v-if="openDetail" :id="id" :title="title" @closeDialog="closeDialog" />
  </div>
</template>

<style lang="scss" scoped>

</style>